package org.github.manx98.jlibhac.hle;

import lombok.Data;
import org.github.manx98.jlibhac.common.math.Uint64;
import org.github.manx98.jlibhac.fs.IStorage;

import java.io.IOException;

/**
 * @author Manx98
 * @version 1.0
 * @since 2022/10/5 23:50
 */
@Data
public class Aci0 {
    private static final int Aci0Magic = 'A' | 'C' << 8 | 'I' << 16 | '0' << 24;

    public Uint64 TitleId;

    public int FsVersion;
    public Uint64 FsPermissionsBitmask;

    public ServiceAccessControl ServiceAccessControl;
    public KernelAccessControl KernelAccessControl;

    public Aci0(IStorage stream, int offset) throws IOException {
        stream.setPosition(offset);

        if (stream.readInt() != Aci0Magic) {
            throw new IllegalArgumentException("ACI0 Stream doesn't contain ACI0 section!");
        }

        stream.setPosition(stream.getPosition() + 0xc);

        TitleId = stream.readUint64();

        // Reserved.
        stream.setPosition(stream.getPosition() + 8);

        int fsAccessHeaderOffset = stream.readInt();
        int fsAccessHeaderSize = stream.readInt();
        int serviceAccessControlOffset = stream.readInt();
        int serviceAccessControlSize = stream.readInt();
        int kernelAccessControlOffset = stream.readInt();
        int kernelAccessControlSize = stream.readInt();

        FsAccessHeader fsAccessHeader = new FsAccessHeader(stream, offset + fsAccessHeaderOffset, fsAccessHeaderSize);

        FsVersion = fsAccessHeader.Version;
        FsPermissionsBitmask = fsAccessHeader.PermissionsBitmask;

        ServiceAccessControl = new ServiceAccessControl(stream, offset + serviceAccessControlOffset, serviceAccessControlSize);

        KernelAccessControl = new KernelAccessControl(stream, offset + kernelAccessControlOffset, kernelAccessControlSize);
    }
}
